package encrypt

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
	"encoding/hex"
)

type S3Desc加解密 struct {
	//V密钥       []byte
	V加密块      cipher.Block
	V是否base64 bool
}

func (a *S3Desc加解密) F解密信息(body string) (string, error) {
	by1, _ := hex.DecodeString(body)

	dst := make([]byte, len(by1))
	//mode := NewECBDecrypter(block)
	DeCryptBlocks(dst, by1, a.V加密块)
	by := PKCS7UnPadding(dst)
	return string(by), nil
}

func DeCryptBlocks(dst, src []byte, block cipher.Block) {
	for len(src) > 0 {
		block.Decrypt(dst, src[:block.BlockSize()])
		src = src[block.BlockSize():]
		dst = dst[block.BlockSize():]
	}
}

// 这个每次加密数值都是一样的。
func F新建3Desc加解密(key ...string) (加解密 *S3Desc加解密, err error) {
	密钥 := F处理密钥格式(key...)
	加解密 = &S3Desc加解密{}
	加解密.V加密块, err = des.NewTripleDESCipher(密钥)
	return
}
func (a *S3Desc加解密) F加密信息(body string) (string, error) {

	blockSize := a.V加密块.BlockSize()
	src := PKCS7Padding([]byte(body), blockSize)

	encryptData := make([]byte, len(src))
	EnCryptBlocks(encryptData, src, a.V加密块)
	return hex.EncodeToString(encryptData), nil
}
func (a *S3Desc加解密) F加密字节(body []byte) (string, error) {

	blockSize := a.V加密块.BlockSize()
	src := PKCS7Padding(body, blockSize)

	encryptData := make([]byte, len(src))
	EnCryptBlocks(encryptData, src, a.V加密块)
	return hex.EncodeToString(encryptData), nil
}

func EnCryptBlocks(encryptData, src []byte, block cipher.Block) {
	for len(src) > 0 {
		block.Encrypt(encryptData, src[:block.BlockSize()])
		src = src[block.BlockSize():]
		encryptData = encryptData[block.BlockSize():]
	}
}

func PKCS7UnPadding(src []byte) []byte {
	length := len(src)
	unpadding := int(src[length-1])
	if length < unpadding {
		return src
	}
	return src[:(length - unpadding)]
}

func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}
